﻿using MyBlog.IRepository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using SQLitePCL;
using SqlSugar.IOC;
using MyBlog.Model;

namespace MyBlog.Repository
{

    public class BaseRepository<TEntity> :
        SimpleClient<TEntity>, //sql仓储模式继承,类必须放接口前面
        IBaseRepository<TEntity>
        where TEntity : class, new()
    {
        public BaseRepository(ISqlSugarClient context = null) : base(context)
        {
            base.Context = DbScoped.Sugar;//获取配置设置进去

        
            //创建一次就好了. 
            {
                //创建数据库
                base.Context.DbMaintenance.CreateDatabase();
                //创建表
                base.Context.CodeFirst.InitTables(
                    typeof(BlogNews),
                    typeof(TypeInfo),
                    typeof(WriterInfo)
                    );
            }
        }

        public async Task<bool> CreateAsync(TEntity entity)
        {
            //异步加入数据库,不用像EF Core要自己实现
            return await base.InsertAsync(entity);
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await base.DeleteByIdAsync(id);
        }

        public async Task<bool> EditAsync(TEntity entity)
        {
            return await base.UpdateAsync(entity);
        }

        //导航查询,查询数据都能成可重写的虚方法
        public virtual async Task<TEntity> FindAsync(int id)
        {
            return await base.GetByIdAsync(id);
        }

        public async Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> func)
        {
            return await base.GetSingleAsync(func);
        }

        public virtual async Task<List<TEntity>> QueryAsync()
        {
            return await base.GetListAsync();
        }

        public virtual async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> func)
        {
            return await base.GetListAsync(func);
        }

        public virtual async Task<List<TEntity>> QueryAsync(int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<TEntity>()
                .ToPageListAsync(page, size, total);

        }

        public virtual async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> func, int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<TEntity>()
                .Where(func)
                .ToPageListAsync(page, size, total);
        }
    }


}
